package com.zjk.toolkit.dynamic.thread.pool.sdk.domain;

import com.alibaba.fastjson.JSON;
import com.zjk.toolkit.dynamic.thread.pool.sdk.domain.entity.ThreadPoolEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@RequiredArgsConstructor
public class DyThreadPoolService implements IDyThreadPoolService{
    private final String applicationName;
    private final Map<String, ThreadPoolExecutor> threadPoolExecutorMap;

    @Override
    public List<ThreadPoolEntity> queryThreadPoolList() {
        Set<String> threadPoolNames = threadPoolExecutorMap.keySet();
        List<ThreadPoolEntity> threadPoolEntityList = new ArrayList<>(threadPoolNames.size());
        for (String threadPoolName : threadPoolNames) {
            ThreadPoolExecutor threadPoolExecutor = threadPoolExecutorMap.get(threadPoolName);
            ThreadPoolEntity threadPoolEntity = new ThreadPoolEntity(applicationName, threadPoolName, threadPoolExecutor);
            threadPoolEntityList.add(threadPoolEntity);
        }
        return threadPoolEntityList;
    }

    @Override
    public ThreadPoolEntity queryThreadPoolByPoolName(String threadPoolName) {
        ThreadPoolExecutor threadPoolExecutor = threadPoolExecutorMap.get(threadPoolName);
        if (threadPoolExecutor == null) {
            return new ThreadPoolEntity(applicationName, threadPoolName);
        }
        return new ThreadPoolEntity(applicationName, threadPoolName, threadPoolExecutor);

    }

    @Override
    public void updateThreadPool(ThreadPoolEntity threadPoolEntity) {
        if (threadPoolEntity == null || !applicationName.equals(threadPoolEntity.getAppName())) {
            return ;
        }
        ThreadPoolExecutor threadPoolExecutor = threadPoolExecutorMap.get(threadPoolEntity.getThreadPoolName());
        if (threadPoolExecutor == null) {
            log.warn("线程池不存在,threadPoolName:{}", threadPoolEntity.getThreadPoolName());
            return ;
        }
        log.info("动态线程池，配置查询 应用名:{} 线程名:{} 池化配置:{}", applicationName, threadPoolEntity.getThreadPoolName(), JSON.toJSONString(threadPoolEntity));
        //设置
        int corePoolSize = threadPoolEntity.getCorePoolSize();
        int maxPoolSize = threadPoolEntity.getMaximumPoolSize();
        if (corePoolSize > maxPoolSize) {
            log.error("核心线程数不能大于最大线程数，核心线程数:{} 最大线程数:{}", corePoolSize, maxPoolSize);
            return ;
        }
        threadPoolExecutor.setMaximumPoolSize(threadPoolEntity.getMaximumPoolSize());
        threadPoolExecutor.setCorePoolSize(threadPoolEntity.getCorePoolSize());
    }

}
